﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Authorize.Core.Entity;
using Microsoft.EntityFrameworkCore;

namespace Authorize.Core.Repository.Implement
{
    public class BaseRepository<TEntity, TKey> : IBaseRepository<TEntity, TKey> where TEntity : BaseEntity<TKey>
    {
        public TEntity Add(TEntity entity)
        {
            using (var context = new AuthDbContext())
            {
                context.Add(entity);
                context.SaveChanges();
            }
            return entity;
        }

        public bool Delete(TKey key)
        {
            using (var context = new AuthDbContext())
            {
                var entity = context.Find<TEntity>(key);
                context.Remove<TEntity>(entity);
                context.SaveChanges();
            }
            return true;
        }

        public TEntity Get(TKey key)
        {
            using (var context = new AuthDbContext())
            {
                return context.Find<TEntity>(key);
            }
        }

        public List<TEntity> GetAll(Expression<Func<TEntity, bool>> query)
        {
            using (var context = new AuthDbContext())
            {
                return context.Set<TEntity>().Where(query).ToList();
            }
        }

        public List<TEntity> GetAll()
        {
            using (var context = new AuthDbContext())
            {
                return context.Set<TEntity>().ToList();
            }
        }

        public async Task<List<TEntity>> GetAllAsync(Expression<Func<TEntity, bool>> query)
        {
            using (var context = new AuthDbContext())
            {
                return context.Set<TEntity>().Where(query).ToList();
            }
        }

        public TEntity GetFirst(Expression<Func<TEntity, bool>> query)
        {
            using (var context = new AuthDbContext())
            {
                return context.Set<TEntity>().FirstOrDefault(query);
            }
        }

        public async Task<TEntity> GetFirstAsync(Expression<Func<TEntity, bool>> query)
        {
            using (var context = new AuthDbContext())
            {
                return await context.Set<TEntity>().FirstOrDefaultAsync(query);
            }
        }

        public TEntity Modify(TEntity entity)
        {
            using (var context = new AuthDbContext())
            {
                context.Set<TEntity>().Update(entity);
                context.SaveChanges();
                return entity;
            }
        }
    }
}
